/**

 @Name：layuiAdmin iframe版主入口
 @Author：贤心
 @Site：http://www.layui.com/admin/
 @License：LPPL
    
 */

layui.extend({
    setter: 'web/kdayunadmin/config' //配置模块
    ,
    admin: 'web/kdayunadmin/lib/admin' //核心模块
    ,
    view: 'web/kdayunadmin/lib/view' //视图渲染模块
    ,
    navbar: 'manager/home/navbar' //左侧的菜单
    ,
    zlPinYin: 'web/kdayunadmin/lib/zlPinYin',
    common: 'manager/home/common'
}).define(['setter', 'admin', 'navbar', 'zlPinYin'], function (exports) {
    var setter = layui.setter,
        element = layui.element,
        admin = layui.admin,
        tabsPage = admin.tabsPage,
        zlPinYin = layui.zlPinYin,
        view = layui.view,
        navbar = layui.navbar(),
        message = new Messenger('index', 'kdayunhome')

        //打开标签页
        ,
        openTabsPage = function (url, text, resid) {
            //遍历页签选项卡
            var matchTo, tabs = $('#LAY_app_tabsheader>li'),
                path = url.replace(/(^http(s*):)|(\?[\s\S]*$)/g, '');
            if (url.indexOf('isnewtab=1') > -1) {
                window.open(url, "_blank");
                return;
            }
            tabs.each(function (index) {
                var li = $(this),
                    layid = li.attr('lay-id'),
                    tempresid = resid ? resid : url;

                if (layid === tempresid) {
                    matchTo = true;
                    tabsPage.index = index;
                }
            });

            text = text || '新标签页';

            if (setter.pageTabs) {
                //如果未在选项卡中匹配到，则追加选项卡
                if (!matchTo) {
                    $(APP_BODY).append([
                        '<div class="layadmin-tabsbody-item layui-show">',
                        '<iframe src="' + url + '" frameborder="0" menuid=' + resid + ' class="layadmin-iframe"></iframe>', '</div>'
                    ].join(''));
                    tabsPage.index = tabs.length;
                    element.tabAdd(FILTER_TAB_TBAS, {
                        title: '<span>' + text + '</span>',
                        id: resid ? resid : url,
                        attr: path
                    });
                    setPrevAndNext();
                    $('.layadmin-tabsbody-shade').show();
                }
            } else {
                var iframe = admin.tabsBody(admin.tabsPage.index).find('.layadmin-iframe');
                iframe[0].contentWindow.location.href = url;
            }

            var $iframe
            if (path.indexOf('/coremodelshow') != -1 && resid) {
                $iframe = $(APP_BODY).find('iframe[menuid="' + resid + '"]');
            }
            else {
                $iframe = $(APP_BODY).find('iframe[src="' + url + '"]');
            }
            $iframe && $iframe.load(function () {
                $('.layadmin-tabsbody-shade').fadeOut('600');
            });

            //定位当前tabs
            element.tabChange(FILTER_TAB_TBAS, resid ? resid : url);
            admin.tabsBodyChange(tabsPage.index, {
                url: resid ? resid : url,
                text: text
            });
        },
        setPrevAndNext = function () {
            var $li = $('.layui-tab-title').children('li')
                , sumwidth = 0
                , totalwidth = $('.layui-tab-title').width();
            for (var i = 0; i < $li.length; i++) {
                sumwidth = sumwidth + $li.eq(i).outerWidth();
            }
            if (sumwidth > totalwidth) {
                $('.layadmin-pagetabs').css({ "padding-left": "40px", "padding-right": "80px" });
                $('.layui-icon-prev').show();
                $('.layui-icon-next').show();
            } else {
                $('.layadmin-pagetabs').css({ "padding-left": "0px", "padding-right": "40px" });
                $('.layui-icon-prev').hide();
                $('.layui-icon-next').hide();
            }
        },



        /**
        * 开启layer的页面
        */
        openLayerPage = function (pageCoinfg, params) {
            var pageId = params.__pageId;
            //页面创建加载完成
            pageId && message.on(pageId, 'onPageLoad', function (msg) {
                let iframes = top.window.document.getElementsByTagName("iframe");
                for (var i = 0; i < iframes.length; i++) {
                    var iframe = iframes[i];
                    if (iframe.contentWindow.location.href.indexOf('=' + pageId) != -1) {
                        message.sendMessage(pageId, 'onSuccess')
                        break;
                    }
                }
            })
            var p = $.extend(pageCoinfg, {
                type: 2,
                area: pageCoinfg.area || ['420px', '240px'],
                success: () => {
                }
                , yes: () => {
                    pageId && message.sendMessage(pageId, 'onYes')
                }
                , no: () => {
                    pageId && message.sendMessage(pageId, 'onCancel')
                }
                , onCanClose: () => {
                   return pageId && message.sendMessage(pageId, 'onCanClose')
				}
                , onClosed: () => {
                    pageId && message.sendMessage(pageId, 'onClosed')
                }, full: () => {
                    pageId && message.sendMessage(pageId, 'onFull')
                }, min: () => {
                    pageId && message.sendMessage(pageId, 'onMin')
                }, resizing: () => {
                    pageId && message.sendMessage(pageId, 'onResizing')
                }, moveEnd: () => {
                    pageId && message.sendMessage(pageId, 'onMoveEnd')
                }, restore: () => {
                    pageId && message.sendMessage(pageId, 'onRestore')
                }
            });
            layer.open(p);
        },
        APP_BODY = '#LAY_app_body',
        FILTER_TAB_TBAS = 'layadmin-layout-tabs',
        $ = layui.$;
    window.addEventListener('message', function (event) {
        if (event.data) {
            let d = JSON.parse(event.data);
            if (d && d.msg == 'openTabPage') {
                openTabsPage(d.params.url, d.params.title, d.params.resid);
            }
            if (d && d.msg == 'openTopPage') {
                openLayerPage(d.params.pageCoinfg, d.params.param);
            }
        }
    });
    //将模块根路径设置为 controller 目录
    layui.config({
        base: setter.base + 'modules/'
    });
    view().autoRender();
    //设置navbar
    navbar.set({
        spreadOne: true,
        elem: '#admin-navbar-side',
        cached: false,
        // data: navs,
        url: layui.cache['contentPath'] + '/core/security/querymenuauth',
        type: 'post'
        /*cached:true,
        url: 'datas/nav.json'*/
    });
    //渲染navbar
    navbar.render();

    //清除缓存
    $('#clearCached').on('click', function () {
        navbar.cleanCached();
        layer.alert('清除完成!', {
            icon: 1,
            title: '系统提示'
        }, function () {
            location.reload(); //刷新
        });
    });

    $('.admin-side-cacheclear').on('click', function () {
        $.ajax({
            url: layui.cache['contentPath'] + '/core/cache/clear',
            type: 'get',
            async: false,
            dataType: 'json',
            contentType: "application/json",
            success: function (result) {
                if (result.state == 'OK')
                    alert('清理服务器缓存完毕！');
                else
                    alert('清理服务器缓存出错：' + result.msg)
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('请求异常!');
            }
        });
    });

    //获取当前用户信息并填充
    $.ajax({
        url: layui.cache['contentPath'] + '/admin/coreuser/querycuruserinfo',
        type: 'post',
        async: false,
        dataType: 'json',
        contentType: "application/json",
        success: function (result) {
            var data = result.obj;
            $('#OBJNAME').html(data.userCursor.OBJNAME);
            $('#ROLENAME').attr('roleid', data.currentRoleId);
            if (data.userCursor.TOUX != undefined && data.userCursor.TOUX != null && data.userCursor.TOUX != '') {
                $('#TOUX').prop('src', layui.cache['contentPath'] + data.userCursor.TOUX);
            } else {
                $('#TOUX').prop('src', layui.cache['contentPath'] + '/static/image/userImg.png');
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('请求异常!');
        },
    });

    layui.event('WM_USERWFG', 'WM_OPENPAGE', null, function (WParam) {
        if (WParam && WParam.url != '' && WParam.text != '') {
            openTabsPage(WParam.url, WParam.text);
        }
        if (d && d.msg == 'openTopPage') {
            openLayerPage(d.params.url, d.params.title, d.params.resid, d.params);
        }
    });

    $('#navbarSearchValue').on('keyup', function (e) {
        navbarSeacherHandle($(this).val(), this)
    });
    $('#navbarSearchIcon').on('click', function () {
        navbarSeacherHandle($(this).siblings('input').val(), this)
    });
    // 点击搜索项 
    $('ul.navbarSearchResult').on('click', 'li', function () {
        var value = $(this).find('cite').html();
        $('ul.navbarSearchResult').removeClass('layui-show').addClass('layui-hide');
        $(this).parent().siblings('input').val('');
        if (!$('#admin-navbar-side').find('[title="' + value + '"]').hasClass('layui-nav-itemed')) {
            $('#admin-navbar-side').find('[title="' + value + '"]').children('a').click();
        }
        // $('#admin-navbar-side').find('[title="' + value + '"]').children('a').click();
        // $('#admin-navbar-side').find('.layui-nav-itemed').removeClass('layui-nav-itemed');
        // $('#admin-navbar-side').find('[title="' + value + '"]').children('a').parents('dd').addClass('layui-nav-itemed');
        // $('#admin-navbar-side').find('[title="' + value + '"]').children('a').parents('li.layui-nav-item').addClass('layui-nav-itemed');
    })

    function navbarSeacherHandle(value, dom) {
        var targetData = $(dom).parent('div.navbar-side-search').siblings('div#admin-navbar-side').find('a'),
            ulItem = $(dom).siblings('ul.navbarSearchResult'),
            num = 0;
        ulItem.html(' ');
        if (value == '') {
            ulItem.addClass('layui-hide').removeClass('layui-show');
            return;
        }
        for (var i = 0; i < targetData.length; i++) {
            // if ($(targetData[i]).find('span.layui-nav-more').length == 0) {
            var matchingTarget = $(targetData[i]).find('cite').html(),
                imgHtml = $(targetData[i]).find('img').length > 0 ? $(targetData[i]).find('img')[0].outerHTML : '<i class="fa fa-file"></i>';

            if (matchingTarget.indexOf(value) != -1 || zlPinYin.A(matchingTarget).toLowerCase().indexOf(value.toLowerCase()) != -1) {
                ulItem.append('<li class="search-result-item">' + imgHtml + '<cite>' + matchingTarget + '</cite></li>');
                //ulItem.append('<li class="search-result-item"><i class="' + 'fa fa-file' + '"></i><cite>' + matchingTarget + '</cite></li>');
                num++;
            }
            // }
        }
        ulItem.removeClass('layui-hide').addClass('layui-show');
        if (num == 0) {
            ulItem.append('<li>未查询到对应数据！</li>')
        }
    }

    // $(document).ready(function () {
    //     $('body').addClass('loaded');
    //     $('#loader-wrapper .load_title').remove();
    // });

    function navbarSeacherHandle(value, dom) {
        var targetData = $(dom).parent('div.navbar-side-search').siblings('div#admin-navbar-side').find('a'),
            ulItem = $(dom).siblings('ul.navbarSearchResult'),
            num = 0;
        ulItem.html(' ');
        if (value == '') {
            ulItem.addClass('layui-hide').removeClass('layui-show');
            return;
        }
        for (var i = 0; i < targetData.length; i++) {
            if ($(targetData[i]).find('span.layui-nav-more').length == 0) {
                var matchingTarget = $(targetData[i]).find('cite').html(),
                    imgHtml = $(targetData[i]).find('img').length > 0 ? $(targetData[i]).find('img')[0].outerHTML : '<i class="fa fa-file"></i>';

                if (matchingTarget.indexOf(value) != -1 || zlPinYin.A(matchingTarget).toLowerCase().indexOf(value.toLowerCase()) != -1) {
                    ulItem.append('<li class="search-result-item">' + imgHtml + '<cite>' + matchingTarget + '</cite></li>');
                    num++;
                }
            }
        }
        ulItem.removeClass('layui-hide').addClass('layui-show');
        if (num == 0) {
            ulItem.append('<li>未查询到对应数据！</li>')
        }
    }
    // $(document).ready(function () {
    //     $('body').addClass('loaded');
    //     $('#loader-wrapper .load_title').remove();
    // });

    //对外输出
    exports('index', {
        openTabsPage: openTabsPage,
        setPrevAndNext: setPrevAndNext
    });
});
